package com.bjc.core.tool.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.bjc.core.bean.response.WxCpUser;
import com.bjc.core.tool.service.IRedisService;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * redis 操作实现类
 * 
 * @author 许自辉
 * @date 2017年7月20日 上午9:12:38
 */
@Component
@Slf4j
public class RedisImpl implements IRedisService {

	@Autowired
	private JedisPool jedisPool;

	@Override
	public Jedis getResource() {
		return jedisPool.getResource();
	}

	@Override
	public void returnResource(Jedis jedis) {
		if (jedis != null && jedisPool != null) {
			jedis.quit();
			jedis.close();
		}
	}

	/**
	 * 设置缓存
	 */
	@Override
	public void set(String key, String value) {
		Jedis jedis = null;
		try {
			jedis = getResource();
			jedis.set(key, value);
			log.info("Redis set success - " + key + ", value:" + value);
		} catch (Exception e) {
			log.error("Redis set error: " + e.getMessage() + " - " + key + ", value:" + value);
		} finally {
			returnResource(jedis);
		}
	}

	/**
	 * 设置缓存 并同时设置有效期
	 * @param seconds 以秒为单位
	 */
	@Override
	public void setex(String key, int seconds, String value) {
		Jedis jedis = null;
		try {
			jedis = getResource();
			jedis.setex(key, seconds, value);
		} catch (Exception e) {
			log.error("Redis set error: " + e.getMessage() + " - " + key + ", value:" + value);
		} finally {
			returnResource(jedis);
		}
	}

	/**
	 * 获取缓存
	 */
	@Override
	public String get(String key) {
		String result = null;
		Jedis jedis = null;
		try {
			jedis = getResource();
			result = jedis.get(key);
			log.info("Redis get success - " + key + ", value:" + result);
		} catch (Exception e) {
			log.error("Redis set error: " + e.getMessage() + " - " + key + ", value:" + result);
		} finally {
			returnResource(jedis);
		}
		return result;
	}

	/**
	 * 删除缓存信息
	 * @return 是否删除成功
	 */
	@Override
	public boolean del(String key) {
		Jedis jedis = null;
		boolean flag = true;
		try {
			jedis = getResource();
			jedis.del(key);
			flag = jedis.exists(key);
			log.info("Redis delete key  success - " + key);
		} catch (Exception e) {
			log.error("Redis error delete key error: " + e.getMessage() + " - " + key);
		} finally {
			returnResource(jedis);
		}
		return !flag;
	}

	@Override
	public WxCpUser getWxuser(String wxuid) {
		Jedis jedis = getResource();
		WxCpUser wxuser = new WxCpUser();
		try {
			List<String> list = jedis.hmget("wx"+wxuid,"userId","name","position","mobile","email","avatar");
			wxuser.setUserId(list.get(0));
			wxuser.setName(list.get(1));
			wxuser.setPosition(list.get(2));
			wxuser.setMobile(list.get(3));
			wxuser.setEmail(list.get(4));
			wxuser.setAvatar(list.get(5));
		} catch (Exception e) {
			log.error("通过wxid获取jedis微信头像异常:"+e.getMessage());
		} finally { 
			returnResource(jedis);
		} 
		return wxuser;
	}

}
